import Taro, { Component } from '@tarojs/taro'
import { ScrollView, View } from '@tarojs/components'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import style from './index.module.scss'
import cityTree from "@/assets/json/cityTree.json"



// const touchMove = function(e:any) {
//   e.preventDefault && e.preventDefault()
//   e.returnValue = false
//   e.stopPropagation && e.stopPropagation()
//   return false
// }
// const node:any = document.getElementById("divADBox")
// console.log(node)
// node.addEventListener("touchmove", touchMove, { passive: false })

//  格式化城市
const formatCity = city => ({ id: city.i, name: city.n, children: city.c })

//  获取城市
const getCity = (str='') => {
  const num = Math.ceil(str.length / 2)
  const arr:any = []
  for (let i=1; i<=num; i++) {
    arr.push(str.substr(0, i * 2))
  }
  return arr
}

//  城市排序
const citySort = list => {
  const city = list.map(item => formatCity(item))
  return city.sort((str1, str2) => str1.name.localeCompare(str2.name, 'zh'))
}


export default class ShareImg extends Component {
  state: any
  props: any

  static propTypes = {
    type: PropTypes.string,
    image: PropTypes.string,
    checked: PropTypes.bool,
    isOpened: PropTypes.bool,
    cityCode: PropTypes.string,
    onClose: PropTypes.func,
    onConfirm: PropTypes.func,
  }

  constructor() {
    super(...arguments)
    this.state = {
      cityList: citySort(cityTree),
      cityCode: undefined,
      checkList: []
    }
  }

  componentWillReceiveProps(nextProps: any) {
    const { cityCode } = this.state
    const touchMove = function(e:any) {
      e.preventDefault && e.preventDefault()
      e.returnValue = false
      e.stopPropagation && e.stopPropagation()
      return false
    }
    // console.log(iNoBounce.disable())
    document.getElementById("select-city").addEventListener("touchmove", touchMove, { passive: false })
    // document.getElementById("select-citya").addEventListener("touchmove", touchMove, { passive: false })
    // document.getElementById("select-cityb").addEventListener("touchmove", touchMove, { passive: false })
    if (nextProps.cityCode !== cityCode) {
      this.setCity(nextProps.cityCode)
    }
  }

  //  写入城市信息
  setCity(id, callback?) {
    const ids = getCity(id)
    const check:any = []

    let list:any = cityTree
    ids.map(id => {
      const ind = list.findIndex(item => item.i === id)
      if (ind >= 0) {
        const { id, name, children } = formatCity(list[ind])
        check.push({ id, name })

        if (children) {
          list = children
        } else {
          callback && callback(check)
        }
      }
    })

    this.setState({
      cityCode: id,
      cityList: citySort(list),
      checkList: check
    })
  }

  //  选择城市
  onSelectCity(id) {
    this.setCity(id, (check) => {
      const names = check.map(item => item.name)
      this.props.onClose()
      this.props.onConfirm(id, names, check)
    })
  }

  //
  onSelectItem(city) {
    const ids = getCity(city.id)
    ids.pop()
    let list:any = cityTree
    ids.map(id => {
      const ind = list.findIndex(item => item.i === id)
      if (ind >= 0) {
        const { children } = formatCity(list[ind])
        if (children) {
          list = children
        }
      }
    })

    this.setState({
      checkKey: ids.length,
      cityList: citySort(list)
    })
  }

  render() {
    const prefixCls = 'select-city'
    const { isOpened, onClose } = this.props
    const { cityList, checkKey, checkList } = this.state
    const bool = isOpened ? 'enter' : 'leave'
    const checkIds = checkList.map(item => item.id)

    // @ts-ignore
    return (
      <View id='select-city' className={style[prefixCls]} >
        <View className={classNames(style[`${prefixCls}-overlay`], `xf-overlay xf-fade-${bool}`)} onClick={onClose}/>
        <View className={classNames(style[`${prefixCls}-popup`], `xf-popup xf-popup--bottom xf-popup--round ${prefixCls}`, {
          [`xf-slide-bottom xf-slide-${bool}`]: !isOpened,
        })}>
          <View className={classNames(style[`${prefixCls}-head`], 'f-g-5')}>
            <View className={classNames(style[`${prefixCls}-head-title`], 't-o-e f-g-5')}>请选择所在地区</View>
            <View className={classNames(style[`${prefixCls}-head-close`], 'bnn-icon f-g-5')} onClick={onClose}>&#xe646;</View>
          </View>

          <View className={classNames(style[`${prefixCls}-check`], 'thin-border__b')}>
            {
              checkList.map((item, key) => {
                return (
                  <View className={classNames(style[`${prefixCls}-check-item`], {
                    [style[`${prefixCls}-check-active`]]: key === checkKey
                  })} onClick={this.onSelectItem.bind(this, item)}>{item.name}</View>
                )
              })
            }
          </View>

          <ScrollView scrollY scrollTop={0} className={classNames(style[`${prefixCls}-city`], 'fy-scrollbar')}>
            {
              cityList.map(city => {
                const bool = checkIds.indexOf(city.id) >= 0
                return (
                  <View className={classNames(style[`${prefixCls}-city-item`], {
                    [style[`${prefixCls}-city-active`]]: bool
                  })} onClick={this.onSelectCity.bind(this, city.id)}>
                    <View className={style[`${prefixCls}-city-left`]}>{city.name}</View>
                    {bool && <View className='bnn-icon'>&#xe645;</View>}
                  </View>
                )
              })
            }
          </ScrollView>
        </View>
      </View>
    )
  }
}
